<?php

namespace Exchange\Controller;

use Think\Controller;

class DuihuanController extends Controller {

    public function _initialize() {
        // echo json_encode(getSignPackage());
        $arr = array(
            "title" => "手指点一点，积分兑好礼！",
            "desc" => "看着的积分再多，不如拿着的手中好礼！还在等什么？",
            "link" => C('BASE_URL').'exchange.php/Duihuan/index',
            "imgUrl" => C('IMG_PATH') . 'uploads/duihuanshare.jpg',
        );
        $this->assign('sharePackage', json_encode($arr));
        $this->assign('signPackage', json_encode(getSignPackage()));
    }

	function getUserInfo(){
		$app = check_app();
		var_dump($app);
		echo "<br/>";
		$openid = wx_openid();
		print_r(check_user($openid));
		
	}
	
    function index() {
        $this->display('start');
    }

	function show() {
		$openid = wx_openid();
		$redirec_url = C('BASE_URL') . 'exchange.php/Duihuan/index';
		$huiyuan = check_user($openid);
		if(check_app() == false){
			if (check_login($openid) == false) {
				redirect(C('common.huiyuan_login').'?redirect_url=' . base64_encode($redirec_url));
				exit;
			}
			if(!$huiyuan){
				checkFans($openid, $redirec_url);
			}
		}
		if ($huiyuan) {
			$store = M('duihuan_store')->where('status=1')->order('sort_id asc')->select();
			$product = M('duihuan_product')->where('sid=1')->select();
			//$where['openid'] = $openid;
			$where['tel'] = $huiyuan['huiyuan_tel'];
			$orders = M('duihuan_orders')->where($where)->find();
			if ($orders) {
				$storeName = M('duihuan_store')->where('id=' . $orders['sid'])->getField('title');
				$this->assign('isexhange', 1);
				$this->assign('storeName', $storeName);
				$this->assign('sid', $orders['sid']);
			}
			$this->assign('list', $store);
			$this->assign('openid', $openid);
			$this->assign('data', $product);
			$this->display('exchange');
		} 
		
    }

    function ajaxProduct() {
        $sid = I('sid');
		$openid = I('openid');
        $huiyuan = check_user($openid);
        $data = M('duihuan_product')->where('sid=' . $sid)->order('sort_id asc,id asc')->select();
        //$where['openid'] = I('openid');
		
		$where['tel'] = $huiyuan['huiyuan_tel'];
        $isexchange = M('duihuan_orders')->where($where)->find();

        foreach ($data as $key => $value) {
            if ($isexchange) {
                $data[$key]['isexchange'] = 1;
                $data[$key]['code'] = $this->getCode($value['id'], I('openid'));
            } else {
                $data[$key]['isexchange'] = 0;
                $data[$key]['code'] = "我要兑换";
            }
        }
        if ($data) {
            $json['status'] = 1;
            $json['data'] = $data;
        } else {
            $json['status'] = 0;
            $json['data'] = "暂无数据~";
        }
        echo json_encode($json);
    }

    private function getCode($pid, $openid) {
        $where['pid'] = $pid;
        $where['openid'] = $openid;
        $code = M('duihuan_orders')->where($where)->getField('id');
        if ($code) {
            return $code;
        } else {
            return "我要兑换";
        }
    }

    /**
     * 
     * @return int
     * 活动时间检测
     */
    private function checkTime() {
        $time = getSysTime();
        $starttime = '2015-11-30 00:00:00';
        $endtime = '2015-12-31 23:59:59';
        //活动开始结束识别
        if ($starttime > $time) {
            return 1;
        } elseif ($time >= $starttime && $time < $endtime) {
            return 2;
        } else {
            return 3;
        }
    }

	
	function getscore(){
		$openid = wx_openid();
		//fj_doScore($openid, 2, 12428,"积分兑换"); //扣除积分
		// $score =   fj_getScore($openid);
		 //echo $score;
	}
    function checkUser() {
        $starttime = '2015-12-25 00:00:00';
        $huiyuan = check_user(wx_openid());
        if (date('Y-m-d', $huiyuan['ctime']) < date('Y-m-d', strtotime($starttime))) {
            $json['status'] = 0;
            $json['info'] = "主人，新购房的业主才能兑换哦~";
        } else {
            $json['status'] = 1;
        }
        $this->ajaxReturn($json);
    }

    /**
     * 兑换
     * 
     */
    function exchange() {
        $json['status'] = 0;
        $sid = I('sid');
        $pid = I('pid');
        $title = I('title');
        $openid = I('openid');
        $gc = M('duihuan_orders');
        $huiyuan = check_user($openid);
		if(!$huiyuan){
			$json['info'] = "非法会员信息~";
            echo json_encode($json);
            exit;
		}
		//file_put_contents('./123.txt',json_encode($huiyuan));
        $score = fj_getScore($openid);
		
        $timevalue = $this->checkTime();
        $product = M('duihuan_product')->where('id=' . $pid)->find(); //产品信息
        if ($product['num'] >= $product['total']) {
            $json['info'] = "手慢了,已经兑完了~";
            echo json_encode($json);
            exit;
        }
        if ($score < $product['score']) {
            $json['info'] = "积分不足";
            echo json_encode($json);
            exit;
        }
        //$where['openid'] = $openid;
		$where['tel'] = $huiyuan['huiyuan_tel'];
        $isexchange = M('duihuan_orders')->where($where)->find(); //检测是否已经参与
        if (!$isexchange) {
            $arr = array(
                'sid' => $sid,
                'pid' => $pid,
                'title' => $title,
                'name' => $huiyuan['huiyuan_name'],
                'tel' => $huiyuan['huiyuan_tel'],
                'openid' => $openid,
                'ctime' => getSysTime(),
            );
            $state = $gc->add($arr);
            if ($state) {
                M('duihuan_product')->where('id=' . $pid)->setInc('num', 1);
                fj_doScore($openid, 2, $product['score'],"积分兑换"); //扣除积分
                $json['status'] = 1;
                $json['key'] = $state;
                $json['pid'] = $pid;
                $json['info'] = "兑换成功";
            } else {
                $json['info'] = "兑换失败";
            }
            echo json_encode($json);
        } else {
            $json['info'] = "已经兑换过了~";
            echo json_encode($json);
        }
    }


    function login() {
        //echo $_SESSION['pxusername'];exit;
        $this->display('submit');
    }

    /**
     * 异步检测登录
     * 
     */
    public function checkLogin() {
        //$gc = M('Exchange_storeuser');
        $json['status'] = 0;
        $name = $_REQUEST['name'];
        $pwd = $_REQUEST['pwd'];
        $data['status'] = 1;
        $where['title'] = $name;
        $data = M('duihuan_store')->where($where)->find();
        if (!$data) {
            $json['info'] = "无效账号";
        } elseif ($pwd != '123456') {
            $json['info'] = "密码错误";
        } elseif ($data['status'] != 1) {
            $json['info'] = "账号异常";
        } else {
            $json['status'] = 1;
            $_SESSION['duihuistoreid'] = $data['id'];
            $_SESSION['duihuanusername'] = $name;
            $str = "登录用户" . $name . ",登录ip地址:" . getcip() . ',登录时间:' . date('Y-m-d H:i:s') . PHP_EOL;
        }
        file_put_contents("./app/Exchange/Controller/duihuanuserlog.txt", $str, FILE_APPEND); //写入登录日志
        $this->ajaxReturn($json);
    }

    /**
     * 核销兑换信息
     * 
     */
    function jydorder() {
        if (!$_SESSION['duihuistoreid']) {
            redirect(__APP__ . '/Duihuan/login');
        } else {
            $this->display('order');
        }
    }

//查询兑奖码
    function getOrderByKey() {
        $gc = M('duihuan_orders');
        $key = intval($_REQUEST['key']);
        $where['id'] = $key;
        $rs = $gc->where($where)->find();
//echo $gc->getLastSql();exit;
        if ($rs) {
            $rs['img'] = getWxBaseInfo($rs['openid']);
            $rs['tel'] = substr_replace($rs['tel'], '****', 3, 4);
            $json['status'] = 1;
            $json['info'] = $rs;
        } else {
            $json['status'] = 0;
            $json['info'] = "key不存在";
        }
        $this->ajaxReturn($json);
    }

//更新兑奖订单信息
    function updatestatus() {
        $gc = M('duihuan_orders');
        $key = $_REQUEST['key'];
        $where['id'] = $key;
        $data = $gc->where($where)->find(); //查询订单数据
        $title = M('duihuan_store')->where('id=' . $data['sid'])->getField('title'); //查询兑换楼盘名
        $json['status'] = 0;
        if ($data['sid'] != $_SESSION['duihuistoreid']) {
            $json['info'] = "兑奖码不是" . $_SESSION['duihuanusername'] . "的,请至" . $title . "兑换";
        } else {
            $rs = $gc->where($where)->save(array('status' => 2, 'utime' => getSysTime()));
            if ($rs) {
                $json['status'] = 1;
                $json['info'] = "兑换成功";
            } else {
                $json['info'] = "兑换失败";
            }
        }


        $this->ajaxReturn($json);
    }

//分项计量
    function sharelog() {
        $arr = array(
            'open_id' => $_REQUEST['openid'],
            'activity_id' => 'duihuanshare',
            'ctime' => time(),
            'utime' => time(),
        );
        M('sharelog')->add($arr);
    }

}
